package com.qlyl.modules.information.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qlyl.common.api.vo.Result;
import com.qlyl.common.constant.CacheConstant;
import com.qlyl.common.constant.CommonConstant;
import com.qlyl.common.constant.SecretkeyContant;
import com.qlyl.common.system.api.ISysBaseAPI;
import com.qlyl.common.util.PasswordUtil;
import com.qlyl.common.util.oConvertUtils;
import com.qlyl.modules.information.entity.AppUser;
import com.qlyl.modules.information.entity.Consumers;
import com.qlyl.modules.information.entity.EthWallet;
import com.qlyl.modules.information.mapper.AppUserMapper;
import com.qlyl.modules.information.mapper.EthWalletMapper;
import com.qlyl.modules.information.service.IAppUserService;
import com.qlyl.modules.information.service.IEthService;
import com.senlin.ethereum.core.EthAccount;
import com.senlin.ethereum.core.EthClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements IAppUserService {


    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private EthWalletMapper ethWalletMapper;
    @Autowired
    private EthClient ethClient;
    @Autowired
    private IEthService ethService;

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    public Result<?> resetPassword(String username, String oldpassword, String newpassword, String confirmpassword) {
        AppUser appUser = appUserMapper.getAppUserByName(username);
        String passwordEncode = PasswordUtil.encrypt(username, oldpassword, appUser.getSalt());
        if (!appUser.getPassword().equals(passwordEncode)) {
            return Result.error("旧密码输入错误!");
        }
        if (oConvertUtils.isEmpty(newpassword)) {
            return Result.error("新密码不允许为空!");
        }
        if (!newpassword.equals(confirmpassword)) {
            return Result.error("两次输入密码不一致!");
        }
        String password = PasswordUtil.encrypt(username, newpassword, appUser.getSalt());
        this.appUserMapper.update(new AppUser().setPassword(password), new LambdaQueryWrapper<AppUser>().eq(AppUser::getId, appUser.getId()));
        return Result.ok("密码重置成功!");
    }

    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    public Result<?> changePassword(AppUser appUser) {
        String salt = oConvertUtils.randomGen(8);
        appUser.setSalt(salt);
        String password = appUser.getPassword();
        String passwordEncode = PasswordUtil.encrypt(appUser.getUsername(), password, salt);
        appUser.setPassword(passwordEncode);
        this.appUserMapper.updateById(appUser);
        return Result.ok("密码修改成功!");
    }

    @Override
    public AppUser getAppUserByName(String username) {
        return appUserMapper.getAppUserByName(username);
    }

    @Override
    public AppUser getAppUserUserByEmail(String email) {
        return appUserMapper.getAppUserByEmail(email);
    }


    @Override
    public AppUser getAppUserByPhone(String cphone) {
        return appUserMapper.getAppUserByPhone(cphone);
    }

    @Override
    @Transactional
    public boolean frozenBatchChcek(String ids, String checkStatus) {
        String[] arr = ids.split(",");
        for (String id : arr) {
            if (oConvertUtils.isNotEmpty(id)) {
                this.update(new AppUser().setBindingStatus(Integer.valueOf(checkStatus)),
                        new UpdateWrapper<AppUser>().lambda().eq(AppUser::getId, id));
            }

        }
        return true;
    }

    /**
     * 校验app用户是否有效
     *
     * @param appUser
     * @return
     */
    @Override
    public Result<?> checkUserIsEffective(AppUser appUser) {
        Result<?> result = new Result<Object>();
        //情况1：根据用户信息查询，该用户不存在
        if (appUser == null) {
            result.error500("该用户不存在，请注册");
            sysBaseAPI.addLog("用户登录失败，用户不存在！", CommonConstant.LOG_TYPE_1, null);
            return result;
        }
        //情况2：根据用户信息查询，该用户已注销
        if (CommonConstant.DEL_FLAG_1.toString().equals(appUser.getDelFlag())) {
            sysBaseAPI.addLog("用户登录失败，用户名:" + appUser.getUsername() + "已注销！", CommonConstant.LOG_TYPE_1, null);
            result.error500("该用户已注销");
            return result;
        }
        //情况3：根据用户信息查询，该用户已冻结
        if (CommonConstant.USER_FREEZE.equals(appUser.getUserStatus())) {
            sysBaseAPI.addLog("用户登录失败，用户名:" + appUser.getUsername() + "已冻结！", CommonConstant.LOG_TYPE_1, null);
            result.error500("该用户已冻结");
            return result;
        }
        return result;
    }

    @Override
    public EthWallet createWallet() {
        EthAccount account= ethClient.createAccount().get();

        EthWallet ethWallet = new EthWallet();
        String walletIdStr  = PasswordUtil.encrypt(account.getMemorizingWords(), SecretkeyContant.SECRET_kEY,SecretkeyContant.SECRET_SALT);
        ethWallet.setAddress(account.getAddress());
        ethWallet.setCreateTime(new Date());
        ethWallet.setMemorizingWords(walletIdStr);
        ethWallet.setPrivateKey(account.getPrivateKey());
        ethWallet.setPublicKey(account.getPublicKey());
        ethWallet.setWalletFilepath(account.getWalletFilePath());
        ethWallet.setBalance(new BigDecimal(0.0000));

        ethWalletMapper.insert(ethWallet);
        return  ethWallet;



    }
}



